import os

from flask import Flask, session, g, request, abort, redirect, url_for
import pymysql
from models import Teacher
from models import Student
from exts import db
import config
from werkzeug.security import generate_password_hash

from flask import Flask, render_template, request, jsonify
import torch
import torch.nn.functional as F
from transformers import BertTokenizer
import dpcnn
import os
import re
from docx import Document
import PyPDF2

from blueprints.student import bp as stu_bp
from blueprints.teacher import bp as tea_bp
from blueprints.login import bp as login_bp
from blueprints.homework import bp as home_bp
from blueprints.homepage import bp as homepage_bp
from blueprints.uploadhomework import bp as upload_bp
from blueprints.copy import bp as copy_bp
from blueprints.AI import bp as AI_bp
from blueprints.question import bp as qs_bp
from blueprints.document import bp as do_bp

# 新增：导入爱国情感提示工程蓝图
from blueprints.patriotic_prompt_engineering import bp as patriotic_prompt_bp

pymysql.install_as_MySQLdb()

app = Flask(__name__)

app.config.from_object(config)
app.register_blueprint(tea_bp)
app.register_blueprint(stu_bp)
app.register_blueprint(home_bp)
app.register_blueprint(login_bp)
app.register_blueprint(homepage_bp)
app.register_blueprint(upload_bp)
app.register_blueprint(copy_bp)
app.register_blueprint(AI_bp)
app.register_blueprint(qs_bp)
app.register_blueprint(do_bp)

# 新增：注册爱国情感提示工程蓝图
app.register_blueprint(patriotic_prompt_bp)

db.init_app(app)

app.config['SECRET_KEY'] = os.urandom(24)

# 新增：确保静态文件目录存在
static_dir = os.path.join(os.getcwd(), 'static')
os.makedirs(static_dir, exist_ok=True)

# 新增：为模板添加过滤器，用于文本分析结果展示
# @app.template_filter('sum')
# def sum_filter(items, attribute=None):
#     """计算列表中指定属性的总和"""
#     if attribute:
#         return sum(getattr(item, attribute, 0) for item in items)
#     else:
#         return sum(item[1] for item in items)


@app.template_filter('sum')
def sum_filter(items, attribute=None):
    """自定义求和过滤器"""
    try:
        if attribute is None:
            # 如果没有指定属性，直接求和
            return sum(items)

        # 处理元组列表 [(word, freq), ...]
        if isinstance(items, list) and items and isinstance(items[0], (list, tuple)):
            if attribute == 1 or attribute == '1':
                return sum(item[1] for item in items)
            else:
                return sum(item[0] for item in items)

        # 处理字典列表 [{'word': 'xxx', 'freq': 123}, ...]
        elif isinstance(items, list) and items and isinstance(items[0], dict):
            return sum(item.get(attribute, 0) for item in items)

        # 处理对象列表
        elif isinstance(items, list) and items and hasattr(items[0], attribute):
            return sum(getattr(item, attribute, 0) for item in items)

        # 默认情况
        else:
            return sum(items)

    except (TypeError, IndexError, KeyError, AttributeError) as e:
        print(f"求和过滤器错误: {e}, 数据: {items}, 属性: {attribute}")
        return 0


def none():  # put application's code here
    # 返回网页文件
    # 添加老师
    print("1321")
    teacher = Teacher(ID=1001, password=generate_password_hash("123456"), name="管理1", email="123456789@qq.com")
    teacher1 = Teacher(ID=1002, password=generate_password_hash("123456"), name="管理2", email="123456789@qq.com")
    teacher2 = Teacher(ID=1003, password=generate_password_hash("123456"), name="管理3", email="123456789@qq.com")
    with app.app_context():
        db.session.add(teacher)
        db.session.add(teacher1)
        db.session.add(teacher2)
        db.session.commit()
    print("123")
    return "添加成功"


with app.app_context():
    db.create_all()
    if len(Teacher.query.all()) == 0:
        none()


# 定义用户为教师或学生
@app.before_request
def my_before_request():
    user_id = session.get("user_id")
    print(session.get("role"))
    if user_id:
        if session.get("role") == 'teacher':
            teacher = Teacher.query.filter_by(ID=user_id).first()
            if teacher:
                print(teacher.name)
                setattr(g, "user", teacher)
            else:
                setattr(g, "user", None)

        else:
            student = Student.query.filter_by(ID=user_id).first()
            if student:
                setattr(g, "user", student)
            else:
                setattr(g, "user", None)
    else:
        setattr(g, "user", None)


@app.context_processor
def my_context_processor():
    return {"user": g.user}


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

# 临时启用调试模式（生产环境慎用！）
#if __name__ == '__main__':
#    app.run(debug=True)  # Flask
    # 或 Django: manage.py runserver --insecure
